package com.zhugang.week04;

import java.util.*;

/**
 * @program algorithms
 * @description: MaxCount
 * @author: chanzhugang
 * @create: 2022/06/18 09:14
 */
public class MaxCount {


    public static void main(String[] args) {
        MaxCount maxCount = new MaxCount();
        int[] data = new int[]{2, 1, 5, 100, 5, 5};
        int res = maxCount.maxCount2(data);
        int count = maxCount.maxCount(data);
        System.out.println("count:" + count + " value:" + res);
    }

    /**
     * 有一组无序数据，找出出现次数最多的数据
     *
     * @param data
     * @return
     */
    public int maxCount(int[] data) {
        // 先排好序
        Arrays.sort(data);

        // 出现最多的次数
        int n = data.length;
        int prev = -1;
        int count = 0;
        int max = -1;
        for (int i = 0; i < n; i++) {
            if (data[i] == prev) {
                count++;
                if (max < count) {
                    max = count;
                }
            } else {
                count = 1;
                prev = data[i];
                if (max < count) {
                    max = count;
                }
            }
        }
        return max;
    }

    public int maxCount2(int[] data) {
        // map 实现
        Map<Integer, Integer> map = new HashMap<>();
        for (int d : data) {
            if (map.containsKey(d)) {
                map.put(d, map.get(d) + 1);
            } else {
                map.put(d, 1);
            }
        }
        Integer maxValue = Collections.max(map.values());
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue().equals(maxValue)) {
                Integer key = entry.getKey();
                return key;
            }
        }
        return -1;
    }
}